import os
import json
import logging
from datetime import datetime
from scenario import Scenario

class RunError(Exception): 
    pass

class RunConfig:
    def __init__(self, run_cfg_path: str = ""):
        self.path = run_cfg_path
        self.name = "run config"
        self.decription = "run config"
        self.created_time = ""
        self.update_time = ""
        self.scenarios: list[Scenario] = []
        if run_cfg_path != None and run_cfg_path != "":
            self.init_from_cfg(run_cfg_path)
    
    def __scenario_realpath(self, scenario_path: str) -> str:
        # check scenario path if exists
        if os.path.exists(scenario_path):
            return scenario_path
        path_tmp = os.path.join(os.path.dirname(os.path.realpath(self.path)), scenario_path)
        if os.path.exists(path_tmp):
            return path_tmp
        path_tmp = os.path.realpath(scenario_path)
        if os.path.exists(path_tmp):
            return path_tmp
        return ""
    
    def init_from_cfg(self, run_cfg_path: str) -> bool: 
        if not os.path.exists(run_cfg_path):
            raise RunError(f"run configuration file {run_cfg_path} not exist")
        
        logging.info(f"init run config from {run_cfg_path}")
        realpath = os.path.realpath(run_cfg_path)
        logging.debug(f"run config path: {run_cfg_path}, real path {realpath}")
        config = None
        with open(realpath, 'r', encoding='utf-8') as json_file:
            config = json.load(json_file)

        if config is None:
            logging.error("run config is empty")
            return False
        
        self.name = config.get("name", "run config")
        self.description = config.get("description", "")
        self.created_time = config.get("created_time", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        self.update_time = config.get("update_time", datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        
        if "scenarios" not in config:
            logging.error("no scenarios in run config")
            return False
        
        scenario_paths = config["scenarios"]
        logging.debug(f"scenario path list: {scenario_paths}")

        if len(scenario_paths) == 0:
            logging.error("scenarios is empty in run config")
            return False
        
        for scenario_path in scenario_paths:
            # check scenario path
            path_tmp = self.__scenario_realpath(scenario_path)
            if path_tmp == "":
                raise RunError(f"scenario path {scenario_path} is not exists")
            logging.debug(f"init scenario config from {path_tmp}")
            self.scenarios.append(Scenario(path_tmp))
        return True
    
    def to_string(self):
        return f"""RunConfig: {self.path}
        Name: {self.name}
        Description: {self.description}
        CreateTime: {self.created_time}
        UpdateTime: {self.update_time}
        Scenarios: {self.scenarios}
        """